package cn.tb.basic.controller;

import cn.tb.basic.exception.BusinessException;
import cn.tb.basic.util.AjaxResult;
import cn.tb.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam(value = "file",required = true) MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extNmae = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(file.getBytes(), extNmae);
            return AjaxResult.me().setResultObj(path);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除对象失败！"+e.getMessage());
        }
    }

    @DeleteMapping   //    /group1/M00/00/05/CgAIC2Kl-aGAC4nSAAMx1hM21Rk498.jpg
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1);// group1/M00/00/05/CgAIC2Kl-aGAC4nSAAMx1hM21Rk498.jpg
            String groupName = pathTmp.substring(0,pathTmp.indexOf("/")); //group1
            String extName = pathTmp.substring(pathTmp.indexOf("/")+1); // M00/00/05/CgAIC2Kl-aGAC4nSAAMx1hM21Rk498.jpg
            FastdfsUtil.delete(groupName, extName);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除对象失败！"+e.getMessage());
        }
    }
}
